<template>
  <div class="treeBox">
    <el-input v-model.trim="filterText" class="w-50 " :prefix-icon="Search" placeholder="请输入内容" />
    <el-tree ref="treeRef" :data="props.treeData" :props="defaultProps" default-expand-all :expand-on-click-node="false"
      :filter-node-method="filterNode" :highlight-current="true" @node-click="clickTree" />
  </div>
</template>

<script lang="ts" setup>
import { ref, watch } from "vue";
import { Search } from "@element-plus/icons-vue";
import { useThrottleFn } from "@vueuse/core";

interface Tree {
  [key: string]: any;
}
const props = defineProps({
  treeData: {
    type: [Array],
    default: [],
  },
});
const emits = defineEmits<{
  (event: "clickHandler", data: number): void;
}>();
// input值
const filterText = ref("");
const treeRef = ref<InstanceType<typeof ElTree>>();

const defaultProps = {
  children: "children",
  label: "label",
};

watch(filterText, (val) => {
  treeRef.value!.filter(val);
});

const filterNode = (value: string, data: Tree) => {
  if (!value) return true;
  return data.label.includes(value);
};

const defaultFirst = () => {
  treeRef.value.setCurrentKey(props.treeData[0].id);
};

const clickTree = (node) => {
  console.log(node, "node");
  let { unitName, unitCode, canCreateSub } = node;

  emits("clickHandler", { unitName, unitCode, canCreateSub });
};

defineExpose({ defaultFirst });
</script>

<style lang="scss" scoped>
::v-deep .is-current,
.is-focusable {
  color: #0052d9;
}

.filter-tree {
  cursor: pointer;
}
</style>
